package com.zx.练习题._2022面试题;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 写一个程序，由两个线程协作，按顺序打印出 1-10，其中一个线程打印奇数，另一个线程打印偶数，且两个线程要交替工作；
 * 例： A 线程打印1，之后B 线程打印2，之后 A 线程打印 3，之后 B 线程打印 4……，直至 1-10
 * 全部打印完毕；
 */
@Slf4j
public class Demo4_2 {

    private static int counter = 1;
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition a = lock.newCondition();
    private static Condition b = lock.newCondition();

    public static void main(String[] args) {

        new Thread(() -> {
            while (counter <= 9) {
                lock.lock();
                try {
                    if (counter % 2 != 0) {
                        log.info("{}", counter);
                        counter++;
                        b.signal();
                    } else {
                        try {
                            a.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "奇数").start();

        new Thread(() -> {
            while (counter <= 10) {
                lock.lock();
                try {
                    if (counter % 2 == 0) {
                        log.info("{}", counter);
                        counter++;
                        a.signal();
                    } else {
                        try {
                            b.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "偶数").start();
    }
}
